<?php


class UserGroup extends DBItem {

	public $Name = null;
	public $IsLocked = false;
	public $idParent = null;
	public $Class;
	public $Comments;
	public $idCreatedBy;
	public $DateCreated;
	public $idModifiedBy;
	public $DateModified;

	public static function FillMetaClass(MetaClass $c){
		$c->SetDBTableName('oxy_user_groups');
		$c->SetAbstractDBFieldName('XClass');
		$c->Name = MetaField::String()->WithLabel('Name');
		$c->IsLocked = MetaField::Boolean();
		$c->idParent = MetaField::ID();
		$c->Comments = MetaField::String()->WithLabel('Comments');
		$c->idCreatedBy = MetaField::ID();
		$c->DateCreated = MetaField::DateTime();
		$c->idModifiedBy = MetaField::ID();
		$c->DateModified = MetaField::DateTime();
	}	
	
	public function GetCode(){ return $this->Name; }
	public function GetTitle(){ return $this->Name; }
	
	protected function OnBeforeSave(){
		$this->idModifiedBy = User::GetCurrent()->id;
		$this->DateModified = new DateTime();
		if ($this->idCreatedBy == null){
			$this->idCreatedBy = $this->idModifiedBy;
			$this->DateCreated = $this->DateModified;
		}
		$this->Class = get_called_class();
	}


	public function GetParent(){ return UserGroup::Retrieve($this->idParent); }
	public function IsDescendantOf($usergroup_or_id){
		for ($x = $this; !is_null($x); $x = $this->GetParent())
			if ($x->IsEqual($usergroup_or_id)) 
				return true;
		return false;
	}
	public function IsAncestorOf($usergroup_or_id){
		$x = $usergroup_or_id instanceof UserGroup ? $usergroup_or_id : UserGroup::Retrieve($usergroup_or_id);
		return is_null($x) ? false : $x->IsDescendantOf($this);
	}
	
	
	
	const idVisitors = -1;
	const idUsers = -2;
	const idAdministrators = -3;
	const idDevelopers = -4;
	
	public function GetSubUserGroups(){ return UserGroup::Select('idParent='.new Sql($this->id)); }
	public function GetUsers(){ return User::Select('idUserGroup='.new Sql($this->id)); }
	
	public static function RetrieveByName($name){	return self::Select('Name='.new Sql($name))->GetFirst(); }
	
}


?>
